<template>
    <div class="question-bank">
      <h1 class="title">语文在线练习</h1>
      
      <el-table 
        :data="filteredQuestions"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
        empty-text="暂无题目数据"
      >
        <el-table-column prop="id" label="ID" width="100" align="center" />
        <el-table-column prop="content" label="题目" width="300" />
        <el-table-column prop="score" label="分值" width="100" align="center" />
        
        <el-table-column label="选项">
          <template #default="{ row }">
            <div v-for="(option, index) in row.options" :key="index">
              {{ String.fromCharCode(65 + index) }}. {{ option }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="answer" label="答案" width="100" align="center" />
        
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row.id)"
              :loading="deletingId === row.id"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页组件 -->
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        @current-change="fetchQuestions"
        layout="prev, pager, next"
        style="margin-top: 20px;"
      />
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, computed } from 'vue';
  import axios from 'axios';
  import { ElMessage, ElMessageBox } from 'element-plus';
  
  // 响应式数据
  const questions = ref([]);
  const loading = ref(false);
  const deletingId = ref(null);
  const error = ref(null);
  
  // 分页数据
  const pagination = ref({
    current: 1,
    size: 10,
    total: 0
  });
  
  // 计算属性确保数据总是数组
  const filteredQuestions = computed(() => {
    return Array.isArray(questions.value) ? questions.value : [];
  });
  
  // 创建axios实例
  const api = axios.create({
    baseURL: 'http://192.168.43.173:8080',
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': localStorage.getItem('token') || ''
    }
  });
  
  // 获取题库数据 - 固定获取语文题目
  const fetchQuestions = async () => {
    try {
      loading.value = true;
      error.value = null;
      
      const response = await api.get('/api/questions', {
        params: {
          subject: 'chinese', // 固定为语文科目
          page: pagination.value.current,
          size: pagination.value.size
        }
      });
  
      // 深度校验数据结构
      if (
        !response.data ||
        response.data.code !== 200 ||
        !response.data.data?.list ||
        !Array.isArray(response.data.data.list)
      ) {
        throw new Error('接口返回结构不符合约定');
      }
  
      // 验证每个题目对象的完整性
      const isValid = response.data.data.list.every(item => {
        return item.id && item.content && item.options && item.answer;
      });
  
      if (!isValid) {
        throw new Error('题目数据字段不完整');
      }
  
      questions.value = response.data.data.list;
      pagination.value.total = response.data.data.total || 0;
      
    } catch (err) {
      console.error('完整错误日志:', {
        error: err,
        request: err.config,
        response: err.response?.data
      });
      
      error.value = err;
      questions.value = [];
      
      let errorMsg = '获取题目失败';
      if (err.response) {
        errorMsg = err.response.data?.message || `服务器错误: ${err.response.status}`;
      } else if (err.request) {
        errorMsg = '网络错误，请检查连接';
      }
      
      ElMessage.error(errorMsg);
    } finally {
      loading.value = false;
    }
  };
  
  // 删除题目
  const handleDelete = async (id) => {
    try {
      await ElMessageBox.confirm('确定要删除这道题目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      
      deletingId.value = id;
      await api.delete(`/api/questions/${id}`);
      ElMessage.success('删除成功');
      await fetchQuestions();
    } catch (err) {
      if (err !== 'cancel') {
        console.error('删除失败:', err);
        ElMessage.error('删除失败: ' + (err.response?.data?.message || err.message));
      }
    } finally {
      deletingId.value = null;
    }
  };
  
  // 页面加载时获取数据
  onMounted(() => {
    fetchQuestions();
  });
  </script>
  
  <style scoped>
  .question-bank {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
  }
  
  .title {
    text-align: center;
    font-size: 28px;
    font-weight: 500;
    margin-bottom: 20px;
    color: #333;
  }
  </style>